var express = require('express');
var multiparty = require('multiparty');
var fs = require('fs');
var util = require('util');
const {Contest} = require('../db');

var copyFile = util.promisify(fs.copyFile);
var unlink = util.promisify(fs.unlink);
var exists = util.promisify(fs.exists);
var mkdir = util.promisify(fs.mkdir);

var router = express.Router();
const UPLOAD_DIR = './public/uploads/';

router.get('/', function(req, res, next) {
    const now = new Date();
    res.render('contest/vacation-photo', {
        year: now.getFullYear(),
        month: now.getMonth() + 1
    });
});

router.post('/vacation-photo/:year/:month', async function(req, res, next) {
    let year = req.params.year;
    let month = req.params.month;
    let prefix = `${year}/${month}/`;
    let serverPath = UPLOAD_DIR + prefix;
    if (!await exists(serverPath)) {
        await mkdir(serverPath, { recursive: true });
    }
    const form = new multiparty.Form();
    form.parse(req, async function(err, fields, files) {
        if(err) {
            res.redirect(303, '/contest/error');
            return;
        }
        //move file to public folder
        let file = files.photo[0];
        let originalFile = file.originalFilename;
        let tempPath = file.path;
        //use tempPath's filename to create a new file
        let targetPath = prefix + tempPath.substring(tempPath.lastIndexOf('/') + 1);
        try {
            await copyFile(tempPath, UPLOAD_DIR + targetPath);
            await unlink(tempPath);
            var contest = new Contest({
                email: fields.email[0],
                name: fields.name[0],
                originalFile: originalFile,
                targetPath: targetPath
            })
            await contest.save();
        } catch(err) {
            console.log(err)
            res.redirect(303, '/contest/error');
            return;
        }
        req.session.uploaded_image = '/uploads/' + targetPath;
        res.redirect(303, '/contest/thank-you');
    });
});

router.get('/thank-you', function(req, res, next) {
    console.log(req.session.uploaded_image);
    res.render('contest/vacation-photo-thank-you', {uploaded_image: req.session.uploaded_image});
});

router.get('/error', function(req, res, next) {
    res.render('contest/vacation-photo-error');
});

module.exports = router;
